import argparse
import logging

import os
import sys

# 环境路径添加
PACKAGE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(PACKAGE_DIR)

import rasa.utils.io

from rasa import version
from rasa.cli import (
    scaffold,
    run,
    train,
    interactive,
    shell,
    test,
    visualize,
    data,
    x,
    export,
)
from rasa.cli.arguments.default_arguments import add_logging_options
from rasa.cli.utils import parse_last_positional_argument_as_model_path
from rasa.utils.common import set_log_level
import rasa.utils.tensorflow.environment as tf_env

logger = logging.getLogger(__name__)


def create_argument_parser() -> argparse.ArgumentParser:
    """解析训练脚本的所有命令行参数"""

    parser = argparse.ArgumentParser(
        prog="rasa",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="Rasa command line interface. Rasa allows you to build "
        "your own conversational assistants 🤖. The 'rasa' command "
        "allows you to easily run most common commands like "
        "creating a new bot, training or evaluating models.",
    )

    parser.add_argument(
        "--version",
        action="store_true",
        default=argparse.SUPPRESS,
        help="Print installed Rasa version",
    )

    # 为parser添加子解析器
    subparsers = parser.add_subparsers(help="Rasa commands")

    # 新建父解析器
    parent_parser = argparse.ArgumentParser(add_help=False)
    add_logging_options(parent_parser)  # 添加日志记录级别参数
    parent_parsers = [parent_parser]    # 获得父解析器列表

    # 具体的子命令行参数
    scaffold.add_subparser(subparsers, parents=parent_parsers)  # 脚手架初始化一个机器人
    run.add_subparser(subparsers, parents=parent_parsers)       # 执行相关的命令行参数
    shell.add_subparser(subparsers, parents=parent_parsers)     # 测试相关的命令行参数
    train.add_subparser(subparsers, parents=parent_parsers)     # 训练相关的命令行参数
    interactive.add_subparser(subparsers, parents=parent_parsers)
    test.add_subparser(subparsers, parents=parent_parsers)
    visualize.add_subparser(subparsers, parents=parent_parsers)
    data.add_subparser(subparsers, parents=parent_parsers)
    export.add_subparser(subparsers, parents=parent_parsers)
    x.add_subparser(subparsers, parents=parent_parsers)

    return parser


def print_version() -> None:
    print("Rasa", version.__version__)


def main() -> None:
    """python应用程序总入口"""

    import os
    import sys

    # 命令行位置参数修复
    parse_last_positional_argument_as_model_path()

    arg_parser = create_argument_parser()           # 新建命令行参数解析器

    cmdline_arguments = arg_parser.parse_args()     # 命令行参数解析

    log_level = (
        cmdline_arguments.loglevel if hasattr(cmdline_arguments, "loglevel") else None
    )

    print("log_level:", log_level)

    set_log_level(log_level)            # 各种日志级别设置的入口
    tf_env.setup_tf_environment()       # 为tensorflow设置cpu和gpu的相关配置
    sys.path.insert(1, os.getcwd())     # 在syspath中插入当前路径，以便找到自定义模块

    print("cmdline_arguments:", cmdline_arguments)

    if hasattr(cmdline_arguments, "func"):
        rasa.utils.io.configure_colored_logging(log_level)
        cmdline_arguments.func(cmdline_arguments)   # 执行入口
    elif hasattr(cmdline_arguments, "version"):
        print_version()
    else:
        # 没有子命令，则打印帮助信息
        logger.error("No command specified.")
        arg_parser.print_help()
        exit(1)


if __name__ == "__main__":
    main()
